package com.hwpt.chesedemo.presentation.theme

import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.text.intl.Locale
import com.hwpt.chesedemo.presentation.component.Difficulty
import com.hwpt.chesedemo.data.local.PreferenceManager

// 多语言资源类
data class StringResources(
    val undo: String,
    val resign: String,
    val draw: String,
    val saveGame: String,
    val savePgn: String,
    val newGame: String,
    val gameOver: String,
    val checkmate: String,
    val stalemate: String,
    val resignation: String,
    val drawAgreed: String,
    val whiteWins: String,
    val blackWins: String,
    val gameDrawn: String,
    val moveHistory: String,
    val gameInfo: String,
    val turn: String,
    val status: String,
    val moveCount: String,
    val inProgress: String,
    val check: String,
    val white: String,
    val black: String,
    val you: String,
    val aiOpponent: String,
    val gameDetails: String,
    val selectAiDifficulty: String,
    val chooseOpponentByLevel: String,
    val tapToStartGame: String,
    val tapToSelectDifficulty: String,
    val select: String,
    // EvaluationScreen 相关
    val evaluation: String,
    val back: String,
    val selectGameData: String,
    val gameRecordSelection: String,
    val pastePgnText: String,
    val noGameRecords: String,
    val win: String,
    val loss: String,
    val drawResult: String,
    val aiDifficulty: String,
    val roundCount: String,
    val pastePgnFormat: String,
    val analyzing: String,
    val startAnalysis: String,
    val analysisResults: String,
    val whitePlayer: String,
    val blackPlayer: String,
    val eloRating: String,
    val strengthMeter: String,
    val accuracy: String,
    val blunders: String,
    val mistakes: String,
    val inaccuracies: String,
    val gameResult: String,
    val gameQuality: String,
    val analyzingDot: String,
    // HomeScreen 相关
    val appTitle: String,
    val appSubtitle: String,
    val battle: String,
    val battleDescription: String,
    val teaching: String,
    val teachingDescription: String,
    val review: String,
    val reviewDescription: String,
    val settings: String,
    val settingsDescription: String,
    // SettingsScreen 相关
    val language: String,
    val aboutUs: String,
    val aboutUsDescription: String,
    val feedback: String,
    val feedbackDescription: String,
    val selectLanguage: String,
    val cancel: String,
    // 难度选择相关
    val difficultyBeginner: String,
    val difficultyIntermediate: String,
    val difficultyAdvanced: String,
    val difficultyExpert: String,
    val difficultyMaster: String,
    val difficultyBeginnerDesc: String,
    val difficultyIntermediateDesc: String,
    val difficultyAdvancedDesc: String,
    val difficultyExpertDesc: String,
    val difficultyMasterDesc: String,
    // AnalysisScreen 相关的新增字段
    val sendingToAI: String,
    val move: String,
    val aiResponse: String,
    val aiResponseLength: String,
    val parsedItemsCount: String,
    val analysisItem: String,
    val totalLines: String,
    val line: String,
    val saveAnalysis: String,
    val foundMove: String,
    val saveLastAnalysis: String,
    val analysisMapSize: String,
    val mapItem: String,
    val foundAnalysis: String,
    val noAnalysis: String,
    val noAnalysisFound: String,
    val fuzzyMatchFound: String,
    val finalItemsCount: String,
    val analysis: String,
    val moveNumber: String,
    val chessboard: String,
    // 游戏结果相关 - 新增
    val resultWhiteWin: String,
    val resultBlackWin: String,
    val resultDraw: String,
    val resultAIWin: String,
    val resultHumanWin: String,
    val resultCheckmate: String,
    val resultStalemate: String,
    val resultResignation: String,
    val resultTimeout: String,
    val resultDisconnection: String,
    // 难度图标
    val difficultyBeginnerIcon: String = "🌱",
    val difficultyIntermediateIcon: String = "📘",
    val difficultyAdvancedIcon: String = "📗",
    val difficultyExpertIcon: String = "📙",
    val difficultyMasterIcon: String = "👑"
)

// 多语言资源提供者
object AppStrings {
    val chinese = StringResources(
        undo = "悔棋",
        resign = "认输",
        draw = "求和",
        saveGame = "保存棋谱",
        savePgn = "保存棋谱",
        newGame = "新游戏",
        gameOver = "游戏结束",
        checkmate = "将死",
        stalemate = "逼和",
        resignation = "认输",
        drawAgreed = "和棋协议",
        whiteWins = "白方胜利",
        blackWins = "黑方胜利",
        gameDrawn = "游戏和棋",
        moveHistory = "走子记录",
        gameInfo = "游戏信息",
        turn = "回合",
        status = "状态",
        moveCount = "步数",
        inProgress = "进行中",
        check = "将军",
        white = "白方",
        black = "黑方",
        you = "您",
        aiOpponent = "AI对手",
        gameDetails = "游戏详情",
        selectAiDifficulty = "选择AI难度",
        chooseOpponentByLevel = "根据您的水平选择合适的对手",
        tapToStartGame = "点击任意难度开始游戏",
        tapToSelectDifficulty = "轻触选择难度开始对局",
        select = "选择",
        // EvaluationScreen 相关
        evaluation = "水平评估",
        back = "返回",
        selectGameData = "选择棋局数据",
        gameRecordSelection = "对战记录选择",
        pastePgnText = "粘贴PGN文本",
        noGameRecords = "暂无对战记录",
        win = "胜利",
        loss = "失败",
        drawResult = "平局",
        aiDifficulty = "AI难度",
        roundCount = "回合数",
        pastePgnFormat = "在此粘贴PGN格式的棋局数据...",
        analyzing = "分析中",
        startAnalysis = "开始分析",
        analysisResults = "分析结果",
        whitePlayer = "白方",
        blackPlayer = "黑方",
        eloRating = "ELO等级分",
        strengthMeter = "实力条",
        accuracy = "精确度",
        blunders = "严重失误",
        mistakes = "失误",
        inaccuracies = "不精确",
        gameResult = "对局结果",
        gameQuality = "对局质量",
        analyzingDot = "分析中...",
        // HomeScreen 相关
        appTitle = "智能国际象棋平台",
        appSubtitle = "提升棋艺，享受对弈乐趣",
        battle = "对战",
        battleDescription = "与AI或真人对手对弈",
        teaching = "教学",
        teachingDescription = "学习国际象棋技巧与策略",
        review = "复盘",
        reviewDescription = "分析过往棋局得失",
        settings = "设置",
        settingsDescription = "个性化应用设置",
        // SettingsScreen 相关
        language = "语言",
        aboutUs = "关于我们",
        aboutUsDescription = "了解更多关于我们的信息",
        feedback = "意见反馈",
        feedbackDescription = "向我们提供宝贵意见",
        selectLanguage = "选择语言",
        cancel = "取消",
        // 难度选择相关
        difficultyBeginner = "新手AI",
        difficultyIntermediate = "入门AI",
        difficultyAdvanced = "进阶AI",
        difficultyExpert = "专家AI",
        difficultyMaster = "大师AI",
        difficultyBeginnerDesc = "适合刚接触下棋的玩家",
        difficultyIntermediateDesc = "适合有一定基础的玩家",
        difficultyAdvancedDesc = "适合经常下棋的玩家",
        difficultyExpertDesc = "挑战高水平AI对手",
        difficultyMasterDesc = "与顶尖AI一较高下",
        // AnalysisScreen 相关的新增字段
        sendingToAI = "发送给AI",
        move = "移动",
        aiResponse = "AI响应",
        aiResponseLength = "AI响应长度",
        parsedItemsCount = "解析项数量",
        analysisItem = "分析项",
        totalLines = "总行数",
        line = "行",
        saveAnalysis = "保存分析",
        foundMove = "找到移动",
        saveLastAnalysis = "保存最后分析",
        analysisMapSize = "分析映射大小",
        mapItem = "映射项",
        foundAnalysis = "找到分析",
        noAnalysis = "AI未提供此步棋的具体分析。",
        noAnalysisFound = "未找到分析",
        fuzzyMatchFound = "模糊匹配找到分析",
        finalItemsCount = "最终生成分析项",
        analysis = "分析",
        moveNumber = "移动编号",
        chessboard = "棋盘",
        // 游戏结果相关 - 新增
        resultWhiteWin = "白方获胜",
        resultBlackWin = "黑方获胜",
        resultDraw = "和棋",
        resultAIWin = "AI获胜",
        resultHumanWin = "玩家获胜",
        resultCheckmate = "将死获胜",
        resultStalemate = "逼和",
        resultResignation = "对手认输",
        resultTimeout = "超时判负",
        resultDisconnection = "对手断线"
    )

    val english = StringResources(
        undo = "Undo",
        resign = "Resign",
        draw = "Draw",
        saveGame = "Save Game",
        savePgn = "Save PGN",
        newGame = "New Game",
        gameOver = "Game Over",
        checkmate = "Checkmate",
        stalemate = "Stalemate",
        resignation = "Resignation",
        drawAgreed = "Draw Agreed",
        whiteWins = "White Wins",
        blackWins = "Black Wins",
        gameDrawn = "Game Drawn",
        moveHistory = "Move History",
        gameInfo = "Game Info",
        turn = "Turn",
        status = "Status",
        moveCount = "Moves",
        inProgress = "In Progress",
        check = "Check",
        white = "White",
        black = "Black",
        you = "You",
        aiOpponent = "AI Opponent",
        gameDetails = "Game Details",
        selectAiDifficulty = "Select AI Difficulty",
        chooseOpponentByLevel = "Choose an opponent based on your skill level",
        tapToStartGame = "Tap any difficulty to start the game",
        tapToSelectDifficulty = "Tap to select difficulty and start",
        select = "Select",
        // EvaluationScreen 相关
        evaluation = "Skill Evaluation",
        back = "Back",
        selectGameData = "Select Game Data",
        gameRecordSelection = "Game Record Selection",
        pastePgnText = "Paste PGN Text",
        noGameRecords = "No game records",
        win = "Win",
        loss = "Loss",
        drawResult = "Draw",
        aiDifficulty = "AI Difficulty",
        roundCount = "Rounds",
        pastePgnFormat = "Paste PGN format game data here...",
        analyzing = "Analyzing",
        startAnalysis = "Start Analysis",
        analysisResults = "Analysis Results",
        whitePlayer = "White",
        blackPlayer = "Black",
        eloRating = "ELO Rating",
        strengthMeter = "Strength Meter",
        accuracy = "Accuracy",
        blunders = "Blunders",
        mistakes = "Mistakes",
        inaccuracies = "Inaccuracies",
        gameResult = "Game Result",
        gameQuality = "Game Quality",
        analyzingDot = "Analyzing...",
        // HomeScreen 相关
        appTitle = "Smart Chess Platform",
        appSubtitle = "Improve your skills, enjoy the game",
        battle = "Battle",
        battleDescription = "Play against AI or human opponents",
        teaching = "Teaching",
        teachingDescription = "Learn chess techniques and strategies",
        review = "Review",
        reviewDescription = "Analyze past game gains and losses",
        settings = "Settings",
        settingsDescription = "Personalized app settings",
        // SettingsScreen 相关
        language = "Language",
        aboutUs = "About Us",
        aboutUsDescription = "Learn more about us",
        feedback = "Feedback",
        feedbackDescription = "Provide valuable feedback to us",
        selectLanguage = "Select Language",
        cancel = "Cancel",
        // 难度选择相关
        difficultyBeginner = "Beginner AI",
        difficultyIntermediate = "Intermediate AI",
        difficultyAdvanced = "Advanced AI",
        difficultyExpert = "Expert AI",
        difficultyMaster = "Master AI",
        difficultyBeginnerDesc = "Suitable for players new to chess",
        difficultyIntermediateDesc = "Suitable for players with some experience",
        difficultyAdvancedDesc = "Suitable for regular players",
        difficultyExpertDesc = "Challenge high-level AI opponents",
        difficultyMasterDesc = "Compete with top-level AI",
        // AnalysisScreen 相关的新增字段
        sendingToAI = "Sending to AI",
        move = "Move",
        aiResponse = "AI Response",
        aiResponseLength = "AI Response Length",
        parsedItemsCount = "Parsed Items Count",
        analysisItem = "Analysis Item",
        totalLines = "Total Lines",
        line = "Line",
        saveAnalysis = "Save Analysis",
        foundMove = "Found Move",
        saveLastAnalysis = "Save Last Analysis",
        analysisMapSize = "Analysis Map Size",
        mapItem = "Map Item",
        foundAnalysis = "Found Analysis",
        noAnalysis = "AI did not provide specific analysis for this move.",
        noAnalysisFound = "No analysis found",
        fuzzyMatchFound = "Fuzzy match found analysis",
        finalItemsCount = "Final generated analysis items",
        analysis = "Analysis",
        moveNumber = "Move Number",
        chessboard = "Chessboard",
        // 游戏结果相关 - 新增
        resultWhiteWin = "White Wins",
        resultBlackWin = "Black Wins",
        resultDraw = "Draw",
        resultAIWin = "AI Wins",
        resultHumanWin = "Human Wins",
        resultCheckmate = "Checkmate",
        resultStalemate = "Stalemate",
        resultResignation = "Opponent Resigned",
        resultTimeout = "Timeout",
        resultDisconnection = "Opponent Disconnected"
    )

    val japanese = StringResources(
        undo = "一手戻る",
        resign = "投了",
        draw = "引き分け",
        saveGame = "棋譜を保存",
        savePgn = "棋譜を保存",
        newGame = "新しいゲーム",
        gameOver = "ゲーム終了",
        checkmate = "チェックメイト",
        stalemate = "ステイルメイト",
        resignation = "投了",
        drawAgreed = "合意による引き分け",
        whiteWins = "白の勝利",
        blackWins = "黒の勝利",
        gameDrawn = "引き分け",
        moveHistory = "手順記録",
        gameInfo = "ゲーム情報",
        turn = "手番",
        status = "状態",
        moveCount = "手数",
        inProgress = "進行中",
        check = "チェック",
        white = "白",
        black = "黒",
        you = "あなた",
        aiOpponent = "AI対戦相手",
        gameDetails = "ゲーム詳細",
        selectAiDifficulty = "AI難易度を選択",
        chooseOpponentByLevel = "あなたのレベルに合った相手を選びましょう",
        tapToStartGame = "任意の難易度をタップしてゲーム開始",
        tapToSelectDifficulty = "難易度を選択して開始",
        select = "選択",
        // EvaluationScreen 相关
        evaluation = "実力評価",
        back = "戻る",
        selectGameData = "棋譜データを選択",
        gameRecordSelection = "対戦記録選択",
        pastePgnText = "PGNテキスト貼り付け",
        noGameRecords = "対戦記録がありません",
        win = "勝利",
        loss = "敗北",
        drawResult = "引き分け",
        aiDifficulty = "AI難易度",
        roundCount = "手数",
        pastePgnFormat = "PGN形式の棋譜データをここに貼り付けてください...",
        analyzing = "分析中",
        startAnalysis = "分析開始",
        analysisResults = "分析結果",
        whitePlayer = "白",
        blackPlayer = "黒",
        eloRating = "ELOレーティング",
        strengthMeter = "実力メーター",
        accuracy = "正確度",
        blunders = "重大なミス",
        mistakes = "ミス",
        inaccuracies = "不正確",
        gameResult = "対局結果",
        gameQuality = "対局品質",
        analyzingDot = "分析中...",
        appTitle = "スマートチェスプラットフォーム",
        appSubtitle = "棋力を向上させ、対局を楽しむ",
        battle = "対戦",
        battleDescription = "AIまたは人間の相手と対局",
        teaching = "教学",
        teachingDescription = "チェスの技術と戦略を学ぶ",
        review = "復習",
        reviewDescription = "過去の棋局を分析",
        settings = "設定",
        settingsDescription = "アプリの個別設定",
        language = "言語",
        aboutUs = "私たちについて",
        aboutUsDescription = "私たちについてもっと知る",
        feedback = "フィードバック",
        feedbackDescription = "貴重なご意見をお寄せください",
        selectLanguage = "言語を選択",
        cancel = "キャンセル",
        difficultyBeginner = "初心者AI",
        difficultyIntermediate = "初級AI",
        difficultyAdvanced = "中級AI",
        difficultyExpert = "上級AI",
        difficultyMaster = "マスターAI",
        difficultyBeginnerDesc = "チェスを始めたばかりのプレイヤー向け",
        difficultyIntermediateDesc = "ある程度経験のあるプレイヤー向け",
        difficultyAdvancedDesc = "定期的にプレイするプレイヤー向け",
        difficultyExpertDesc = "高レベルAIとの対戦",
        difficultyMasterDesc = "トップレベルAIとの対戦",
        // AnalysisScreen 相关的新增字段
        sendingToAI = "AIに送信",
        move = "手",
        aiResponse = "AI応答",
        aiResponseLength = "AI応答の長さ",
        parsedItemsCount = "解析された項目数",
        analysisItem = "分析項目",
        totalLines = "総行数",
        line = "行",
        saveAnalysis = "分析を保存",
        foundMove = "手を見つけました",
        saveLastAnalysis = "最後の分析を保存",
        analysisMapSize = "分析マップのサイズ",
        mapItem = "マップ項目",
        foundAnalysis = "分析を見つけました",
        noAnalysis = "AIはこの手の具体的な分析を提供していません。",
        noAnalysisFound = "分析が見つかりません",
        fuzzyMatchFound = "あいまい一致で分析が見つかりました",
        finalItemsCount = "最終的に生成された分析項目",
        analysis = "分析",
        moveNumber = "手番",
        chessboard = "チェス盤",
        // 游戏结果相关 - 新增
        resultWhiteWin = "白の勝利",
        resultBlackWin = "黒の勝利",
        resultDraw = "引き分け",
        resultAIWin = "AIの勝利",
        resultHumanWin = "プレイヤーの勝利",
        resultCheckmate = "チェックメイト",
        resultStalemate = "ステイルメイト",
        resultResignation = "相手が投了",
        resultTimeout = "タイムアウト",
        resultDisconnection = "相手が切断"
    )

    val korean = StringResources(
        undo = "무르기",
        resign = "기권",
        draw = "무승부",
        saveGame = "기보 저장",
        savePgn = "기보 저장",
        newGame = "새 게임",
        gameOver = "게임 종료",
        checkmate = "체크메이트",
        stalemate = "스테일메이트",
        resignation = "기권",
        drawAgreed = "합의 무승부",
        whiteWins = "백 승리",
        blackWins = "흑 승리",
        gameDrawn = "무승부",
        moveHistory = "수순 기록",
        gameInfo = "게임 정보",
        turn = "턴",
        status = "상태",
        moveCount = "수",
        inProgress = "진행 중",
        check = "체크",
        white = "백",
        black = "흑",
        you = "당신",
        aiOpponent = "AI 상대",
        gameDetails = "게임 상세",
        selectAiDifficulty = "AI 난이도 선택",
        chooseOpponentByLevel = "실력에 맞는 상대를 선택하세요",
        tapToStartGame = "아무 난이도나 탭하여 게임 시작",
        tapToSelectDifficulty = "난이도 선택하여 시작",
        select = "선택",
        evaluation = "실력 평가",
        back = "뒤로",
        selectGameData = "게임 데이터 선택",
        gameRecordSelection = "대전 기록 선택",
        pastePgnText = "PGN 텍스트 붙여넣기",
        noGameRecords = "대전 기록 없음",
        win = "승리",
        loss = "패배",
        drawResult = "무승부",
        aiDifficulty = "AI 난이도",
        roundCount = "라운드 수",
        pastePgnFormat = "PGN 형식의 게임 데이터를 여기에 붙여넣으세요...",
        analyzing = "분석 중",
        startAnalysis = "분석 시작",
        analysisResults = "분석 결과",
        whitePlayer = "백",
        blackPlayer = "흑",
        eloRating = "ELO 레이팅",
        strengthMeter = "실력 미터",
        accuracy = "정확도",
        blunders = "심각한 실수",
        mistakes = "실수",
        inaccuracies = "부정확",
        gameResult = "게임 결과",
        gameQuality = "게임 품질",
        analyzingDot = "분석 중...",
        appTitle = "스마트 체스 플랫폼",
        appSubtitle = "실력 향상, 대국의 즐거움",
        battle = "대전",
        battleDescription = "AI 또는 인간 상대와 대국",
        teaching = "교육",
        teachingDescription = "체스 기술과 전략 학습",
        review = "복기",
        reviewDescription = "과거 기보 분석",
        settings = "설정",
        settingsDescription = "개인화된 앱 설정",
        language = "언어",
        aboutUs = "회사 소개",
        aboutUsDescription = "회사에 대해 자세히 알아보기",
        feedback = "피드백",
        feedbackDescription = "소중한 의견을 제공해 주세요",
        selectLanguage = "언어 선택",
        cancel = "취소",
        difficultyBeginner = "초보자 AI",
        difficultyIntermediate = "초급 AI",
        difficultyAdvanced = "중급 AI",
        difficultyExpert = "고급 AI",
        difficultyMaster = "마스터 AI",
        difficultyBeginnerDesc = "체스를 막 시작한 플레이어에게 적합",
        difficultyIntermediateDesc = "어느 정도 경험이 있는 플레이어에게 적합",
        difficultyAdvancedDesc = "정기적으로 플레이하는 플레이어에게 적합",
        difficultyExpertDesc = "고수준 AI 상대와 도전",
        difficultyMasterDesc = "최고 수준 AI와 경쟁",
        // AnalysisScreen 相关的新增字段
        sendingToAI = "AI로 보내는 중",
        move = "수",
        aiResponse = "AI 응답",
        aiResponseLength = "AI 응답 길이",
        parsedItemsCount = "분석된 항목 수",
        analysisItem = "분석 항목",
        totalLines = "총 줄 수",
        line = "줄",
        saveAnalysis = "분석 저장",
        foundMove = "수를 찾았습니다",
        saveLastAnalysis = "마지막 분석 저장",
        analysisMapSize = "분석 맵 크기",
        mapItem = "맵 항목",
        foundAnalysis = "분석을 찾았습니다",
        noAnalysis = "AI가 이 수에 대한 구체적인 분석을 제공하지 않았습니다.",
        noAnalysisFound = "분석을 찾을 수 없음",
        fuzzyMatchFound = "퍼지 매칭으로 분석을 찾았습니다",
        finalItemsCount = "최종 생성된 분석 항목",
        analysis = "분석",
        moveNumber = "수 번호",
        chessboard = "체스판",
        // 游戏结果相关 - 新增
        resultWhiteWin = "백 승리",
        resultBlackWin = "흑 승리",
        resultDraw = "무승부",
        resultAIWin = "AI 승리",
        resultHumanWin = "플레이어 승리",
        resultCheckmate = "체크메이트",
        resultStalemate = "스테일메이트",
        resultResignation = "상대 기권",
        resultTimeout = "시간 초과",
        resultDisconnection = "상대 연결 끊김"
    )

    val spanish = StringResources(
        undo = "Deshacer",
        resign = "Rendirse",
        draw = "Tablas",
        saveGame = "Guardar partida",
        savePgn = "Guardar PGN",
        newGame = "Nuevo juego",
        gameOver = "Juego terminado",
        checkmate = "Jaque mate",
        stalemate = "Ahogado",
        resignation = "Rendición",
        drawAgreed = "Tablas acordadas",
        whiteWins = "Blancas ganan",
        blackWins = "Negras ganan",
        gameDrawn = "Partida empatada",
        moveHistory = "Historial de movimientos",
        gameInfo = "Información del juego",
        turn = "Turno",
        status = "Estado",
        moveCount = "Movimientos",
        inProgress = "En progreso",
        check = "Jaque",
        white = "Blancas",
        black = "Negras",
        you = "Tú",
        aiOpponent = "Oponente IA",
        gameDetails = "Detalles del juego",
        selectAiDifficulty = "Seleccionar Dificultad de IA",
        chooseOpponentByLevel = "Elige un oponente según tu nivel de habilidad",
        tapToStartGame = "Toca cualquier dificultad para comenzar el juego",
        tapToSelectDifficulty = "Toca para seleccionar dificultad y comenzar",
        select = "Seleccionar",
        // EvaluationScreen 相关
        evaluation = "Evaluación de Habilidad",
        back = "Atrás",
        selectGameData = "Seleccionar Datos del Juego",
        gameRecordSelection = "Selección de Registros",
        pastePgnText = "Pegar Texto PGN",
        noGameRecords = "Sin registros de juego",
        win = "Victoria",
        loss = "Derrota",
        drawResult = "Empate",
        aiDifficulty = "Dificultad de IA",
        roundCount = "Rondas",
        pastePgnFormat = "Pega datos de juego en formato PGN aquí...",
        analyzing = "Analizando",
        startAnalysis = "Iniciar Análisis",
        analysisResults = "Resultados del Análisis",
        whitePlayer = "Blancas",
        blackPlayer = "Negras",
        eloRating = "Puntuación ELO",
        strengthMeter = "Medidor de Fuerza",
        accuracy = "Precisión",
        blunders = "Errores Graves",
        mistakes = "Errores",
        inaccuracies = "Imprecisiones",
        gameResult = "Resultado del Juego",
        gameQuality = "Calidad del Juego",
        analyzingDot = "Analizando...",
        // HomeScreen 相关
        appTitle = "Plataforma de Ajedrez Inteligente",
        appSubtitle = "Mejora tus habilidades, disfruta del juego",
        battle = "Batalla",
        battleDescription = "Juega contra IA u oponentes humanos",
        teaching = "Enseñanza",
        teachingDescription = "Aprende técnicas y estrategias de ajedrez",
        review = "Revisión",
        reviewDescription = "Analiza partidas anteriores",
        settings = "Configuración",
        settingsDescription = "Configuración personalizada de la aplicación",
        // SettingsScreen 相关
        language = "Idioma",
        aboutUs = "Acerca de Nosotros",
        aboutUsDescription = "Aprende más sobre nosotros",
        feedback = "Comentarios",
        feedbackDescription = "Proporciona comentarios valiosos",
        selectLanguage = "Seleccionar Idioma",
        cancel = "Cancelar",
        // 难度选择相关
        difficultyBeginner = "IA Principiante",
        difficultyIntermediate = "IA Intermedia",
        difficultyAdvanced = "IA Avanzada",
        difficultyExpert = "IA Experta",
        difficultyMaster = "IA Maestra",
        difficultyBeginnerDesc = "Adecuado para jugadores nuevos en ajedrez",
        difficultyIntermediateDesc = "Adecuado para jugadores con algo de experiencia",
        difficultyAdvancedDesc = "Adecuado para jugadores regulares",
        difficultyExpertDesc = "Desafía a oponentes IA de alto nivel",
        difficultyMasterDesc = "Compite con IA de nivel superior",
        // AnalysisScreen 相关的新增字段
        sendingToAI = "Enviando a IA",
        move = "Movimiento",
        aiResponse = "Respuesta de IA",
        aiResponseLength = "Longitud de respuesta de IA",
        parsedItemsCount = "Número de elementos analizados",
        analysisItem = "Elemento de análisis",
        totalLines = "Líneas totales",
        line = "Línea",
        saveAnalysis = "Guardar análisis",
        foundMove = "Movimiento encontrado",
        saveLastAnalysis = "Guardar último análisis",
        analysisMapSize = "Tamaño del mapa de análisis",
        mapItem = "Elemento del mapa",
        foundAnalysis = "Análisis encontrado",
        noAnalysis = "La IA no proporcionó un análisis específico para este movimiento.",
        noAnalysisFound = "Análisis no encontrado",
        fuzzyMatchFound = "Coincidencia difusa encontrada en el análisis",
        finalItemsCount = "Elementos de análisis finales generados",
        analysis = "Análisis",
        moveNumber = "Número de movimiento",
        chessboard = "Tablero de ajedrez",
        // 游戏结果相关 - 新增
        resultWhiteWin = "Blancas Ganan",
        resultBlackWin = "Negras Ganan",
        resultDraw = "Tablas",
        resultAIWin = "IA Gana",
        resultHumanWin = "Humano Gana",
        resultCheckmate = "Jaque Mate",
        resultStalemate = "Ahogado",
        resultResignation = "Oponente se Rindió",
        resultTimeout = "Tiempo Agotado",
        resultDisconnection = "Oponente Desconectado"
    )

    val french = StringResources(
        undo = "Annuler",
        resign = "Abandonner",
        draw = "Nulle",
        saveGame = "Sauvegarder",
        savePgn = "Sauvegarder PGN",
        newGame = "Nouvelle partie",
        gameOver = "Partie terminée",
        checkmate = "Échec et mat",
        stalemate = "Pat",
        resignation = "Abandon",
        drawAgreed = "Nulle convenue",
        whiteWins = "Blancs gagnent",
        blackWins = "Noirs gagnent",
        gameDrawn = "Partie nulle",
        moveHistory = "Historique des coups",
        gameInfo = "Informations du jeu",
        turn = "Tour",
        status = "Statut",
        moveCount = "Coups",
        inProgress = "En cours",
        check = "Échec",
        white = "Blancs",
        black = "Noirs",
        you = "Vous",
        aiOpponent = "Adversaire IA",
        gameDetails = "Détails du jeu",
        selectAiDifficulty = "Sélectionner la Difficulté de l'IA",
        chooseOpponentByLevel = "Choisissez un adversaire selon votre niveau",
        tapToStartGame = "Appuyez sur n'importe quelle difficulté pour commencer le jeu",
        tapToSelectDifficulty = "Appuyez pour sélectionner la difficulté et commencer",
        select = "Sélectionner",
        // EvaluationScreen 相关
        evaluation = "Évaluation des Compétences",
        back = "Retour",
        selectGameData = "Sélectionner les Données de Partie",
        gameRecordSelection = "Sélection d'Enregistrements",
        pastePgnText = "Coller le Texte PGN",
        noGameRecords = "Aucun enregistrement de partie",
        win = "Victoire",
        loss = "Défaite",
        drawResult = "Match Nul",
        aiDifficulty = "Difficulté IA",
        roundCount = "Tours",
        pastePgnFormat = "Collez les données de partie au format PGN ici...",
        analyzing = "Analyse en cours",
        startAnalysis = "Commencer l'Analyse",
        analysisResults = "Résultats de l'Analyse",
        whitePlayer = "Blancs",
        blackPlayer = "Noirs",
        eloRating = "Classement ELO",
        strengthMeter = "Jauge de Force",
        accuracy = "Précision",
        blunders = "Erreurs Graves",
        mistakes = "Errores",
        inaccuracies = "Imprécisions",
        gameResult = "Résultat de la Partie",
        gameQuality = "Qualité de la Partie",
        analyzingDot = "Analyse en cours...",
        // HomeScreen 相关
        appTitle = "Plateforme d'Échecs Intelligente",
        appSubtitle = "Améliorez vos compétences, profitez du jeu",
        battle = "Combat",
        battleDescription = "Jouez contre l'IA ou des adversaires humains",
        teaching = "Enseignement",
        teachingDescription = "Apprenez les techniques et stratégies d'échecs",
        review = "Révision",
        reviewDescription = "Analysez les parties précédentes",
        settings = "Paramètres",
        settingsDescription = "Paramètres personnalisés de l'application",
        // SettingsScreen 相关
        language = "Langue",
        aboutUs = "À Propos de Nous",
        aboutUsDescription = "En savoir plus sur nous",
        feedback = "Retour d'Information",
        feedbackDescription = "Fournissez des commentaires précieux",
        selectLanguage = "Sélectionner la Langue",
        cancel = "Annuler",
        // 难度选择相关
        difficultyBeginner = "IA Débutant",
        difficultyIntermediate = "IA Intermédiaire",
        difficultyAdvanced = "IA Avancée",
        difficultyExpert = "IA Experte",
        difficultyMaster = "IA Maître",
        difficultyBeginnerDesc = "Convient aux joueurs débutants aux échecs",
        difficultyIntermediateDesc = "Convient aux joueurs ayant une certaine expérience",
        difficultyAdvancedDesc = "Convient aux joueurs réguliers",
        difficultyExpertDesc = "Défiez des adversaires IA de haut niveau",
        difficultyMasterDesc = "Affrontez l'IA de niveau supérieur",
        // AnalysisScreen 相关的新增字段
        sendingToAI = "Envoi à l'IA",
        move = "Coup",
        aiResponse = "Réponse de l'IA",
        aiResponseLength = "Longueur de la réponse de l'IA",
        parsedItemsCount = "Nombre d'éléments analysés",
        analysisItem = "Élément d'analyse",
        totalLines = "Lignes totales",
        line = "Ligne",
        saveAnalysis = "Enregistrer l'analyse",
        foundMove = "Coup trouvé",
        saveLastAnalysis = "Enregistrer la dernière analyse",
        analysisMapSize = "Taille de la carte d'analyse",
        mapItem = "Élément de la carte",
        foundAnalysis = "Analyse trouvée",
        noAnalysis = "L'IA n'a pas fourni d'analyse spécifique pour ce coup.",
        noAnalysisFound = "Analyse non trouvée",
        fuzzyMatchFound = "Correspondance floue trouvée dans l'analyse",
        finalItemsCount = "Éléments d'analyse finaux générés",
        analysis = "Analyse",
        moveNumber = "Numéro de coup",
        chessboard = "Échiquier",
        // 游戏结果相关 - 新增
        resultWhiteWin = "Blancs Gagnent",
        resultBlackWin = "Noirs Gagnent",
        resultDraw = "Nulle",
        resultAIWin = "IA Gagne",
        resultHumanWin = "Humain Gagne",
        resultCheckmate = "Échec et Mat",
        resultStalemate = "Pat",
        resultResignation = "Adversaire Abandonné",
        resultTimeout = "Temps Écoulé",
        resultDisconnection = "Adversaire Déconnecté"
    )

    val german = StringResources(
        undo = "Rückgängig",
        resign = "Aufgeben",
        draw = "Remis",
        saveGame = "Spiel speichern",
        savePgn = "PGN speichern",
        newGame = "Neues Spiel",
        gameOver = "Spiel beendet",
        checkmate = "Schachmatt",
        stalemate = "Patt",
        resignation = "Aufgabe",
        drawAgreed = "Remis vereinbart",
        whiteWins = "Weiß gewinnt",
        blackWins = "Schwarz gewinnt",
        gameDrawn = "Unentschieden",
        moveHistory = "Zugverlauf",
        gameInfo = "Spielinformationen",
        turn = "Zug",
        status = "Status",
        moveCount = "Züge",
        inProgress = "Im Gange",
        check = "Schach",
        white = "Weiß",
        black = "Schwarz",
        you = "Sie",
        aiOpponent = "KI-Gegner",
        gameDetails = "Spieldetails",
        selectAiDifficulty = "KI-Schwierigkeit wählen",
        chooseOpponentByLevel = "Wählen Sie einen Gegner basierend auf Ihrem Können",
        tapToStartGame = "Tippen Sie auf eine beliebige Schwierigkeit, um das Spiel zu starten",
        tapToSelectDifficulty = "Tippen Sie, um Schwierigkeit auszuwählen und zu starten",
        select = "Auswählen",
        // EvaluationScreen 相关
        evaluation = "Fähigkeitsbewertung",
        back = "Zurück",
        selectGameData = "Spieldaten auswählen",
        gameRecordSelection = "Spielaufzeichnungen Auswahl",
        pastePgnText = "PGN-Text einfügen",
        noGameRecords = "Keine Spielaufzeichnungen",
        win = "Sieg",
        loss = "Niederlage",
        drawResult = "Unentschieden",
        aiDifficulty = "KI-Schwierigkeit",
        roundCount = "Runden",
        pastePgnFormat = "Fügen Sie hier Spieldaten im PGN-Format ein...",
        analyzing = "Analysiere",
        startAnalysis = "Analyse starten",
        analysisResults = "Analyseergebnisse",
        whitePlayer = "Weiß",
        blackPlayer = "Schwarz",
        eloRating = "ELO-Wertung",
        strengthMeter = "Stärkemesser",
        accuracy = "Genauigkeit",
        blunders = "Schwere Fehler",
        mistakes = "Fehler",
        inaccuracies = "Ungenauigkeiten",
        gameResult = "Spielergebnis",
        gameQuality = "Spielqualität",
        analyzingDot = "Analysiere...",
        // HomeScreen 相关
        appTitle = "Intelligente Schachplattform",
        appSubtitle = "Verbessern Sie Ihre Fähigkeiten, genießen Sie das Spiel",
        battle = "Kampf",
        battleDescription = "Spielen Sie gegen KI oder menschliche Gegner",
        teaching = "Lehre",
        teachingDescription = "Lernen Sie Schachtechniken und Strategien",
        review = "Überprüfung",
        reviewDescription = "Analysieren Sie vergangene Spiele",
        settings = "Einstellungen",
        settingsDescription = "Personalisierte App-Einstellungen",
        // SettingsScreen 相关
        language = "Sprache",
        aboutUs = "Über Uns",
        aboutUsDescription = "Erfahren Sie mehr über uns",
        feedback = "Feedback",
        feedbackDescription = "Teilen Sie uns Ihr wertvolles Feedback mit",
        selectLanguage = "Sprache auswählen",
        cancel = "Abbrechen",
        // 难度选择相关
        difficultyBeginner = "Anfänger-KI",
        difficultyIntermediate = "Fortgeschrittene-KI",
        difficultyAdvanced = "Erfahrene-KI",
        difficultyExpert = "Experten-KI",
        difficultyMaster = "Meister-KI",
        difficultyBeginnerDesc = "Geeignet für neue Schachspieler",
        difficultyIntermediateDesc = "Geeignet für Spieler mit etwas Erfahrung",
        difficultyAdvancedDesc = "Geeignet für regelmäßige Spieler",
        difficultyExpertDesc = "Fordern Sie hochrangige KI-Gegner heraus",
        difficultyMasterDesc = "Treten Sie gegen KI der Spitzenklasse an",
        // AnalysisScreen 相关的新增字段
        sendingToAI = "An KI senden",
        move = "Zug",
        aiResponse = "KI-Antwort",
        aiResponseLength = "Länge der KI-Antwort",
        parsedItemsCount = "Anzahl analysierter Elemente",
        analysisItem = "Analyseelement",
        totalLines = "Gesamtzeilen",
        line = "Zeile",
        saveAnalysis = "Analyse speichern",
        foundMove = "Zug gefunden",
        saveLastAnalysis = "Letzte Analyse speichern",
        analysisMapSize = "Größe der Analysemap",
        mapItem = "Map-Element",
        foundAnalysis = "Analyse gefunden",
        noAnalysis = "Die KI hat für diesen Zug keine spezifische Analyse bereitgestellt.",
        noAnalysisFound = "Analyse nicht gefunden",
        fuzzyMatchFound = "Ungefähre Übereinstimmung in der Analyse gefunden",
        finalItemsCount = "Endgültig generierte Analysen",
        analysis = "Analyse",
        moveNumber = "Zugnummer",
        chessboard = "Schachbrett",
        // 游戏结果相关 - 新增
        resultWhiteWin = "Weiß Gewinnt",
        resultBlackWin = "Schwarz Gewinnt",
        resultDraw = "Remis",
        resultAIWin = "KI Gewinnt",
        resultHumanWin = "Mensch Gewinnt",
        resultCheckmate = "Schachmatt",
        resultStalemate = "Patt",
        resultResignation = "Gegner Aufgabe",
        resultTimeout = "Zeitüberschreitung",
        resultDisconnection = "Gegner Verbindung Verloren"
    )

    val russian = StringResources(
        undo = "Отменить",
        resign = "Сдаться",
        draw = "Ничья",
        saveGame = "Сохранить игру",
        savePgn = "Сохранить PGN",
        newGame = "Новая игра",
        gameOver = "Игра окончена",
        checkmate = "Мат",
        stalemate = "Пат",
        resignation = "Сдача",
        drawAgreed = "Ничья по соглашению",
        whiteWins = "Белые выиграли",
        blackWins = "Чёрные выиграли",
        gameDrawn = "Ничья",
        moveHistory = "История ходов",
        gameInfo = "Информация об игре",
        turn = "Ход",
        status = "Статус",
        moveCount = "Ходы",
        inProgress = "В процессе",
        check = "Шах",
        white = "Белые",
        black = "Чёрные",
        you = "Вы",
        aiOpponent = "ИИ-соперник",
        gameDetails = "Детали игры",
        selectAiDifficulty = "Выбрать сложность ИИ",
        chooseOpponentByLevel = "Выберите противника по вашему уровню",
        tapToStartGame = "Нажмите на любую сложность, чтобы начать игру",
        tapToSelectDifficulty = "Нажмите для выбора сложности и начала",
        select = "Выбрать",
        // EvaluationScreen 相关
        evaluation = "Оценка Уровня",
        back = "Назад",
        selectGameData = "Выбрать Данные Игры",
        gameRecordSelection = "Выбор Записей",
        pastePgnText = "Вставить Текст PGN",
        noGameRecords = "Нет записей игр",
        win = "Победа",
        loss = "Поражение",
        drawResult = "Ничья",
        aiDifficulty = "Сложность ИИ",
        roundCount = "Раунды",
        pastePgnFormat = "Вставьте данные игры в формате PGN здесь...",
        analyzing = "Анализ",
        startAnalysis = "Начать Анализ",
        analysisResults = "Результаты Анализа",
        whitePlayer = "Белые",
        blackPlayer = "Чёрные",
        eloRating = "Рейтинг ELO",
        strengthMeter = "Измеритель Силы",
        accuracy = "Точность",
        blunders = "Грубые Ошибки",
        mistakes = "Ошибки",
        inaccuracies = "Неточности",
        gameResult = "Результат Игры",
        gameQuality = "Качество Игры",
        analyzingDot = "Анализ...",
        // HomeScreen 相关
        appTitle = "Умная Шахматная Платформа",
        appSubtitle = "Улучшайте навыки, наслаждайтесь игрой",
        battle = "Битва",
        battleDescription = "Играйте против ИИ или людей",
        teaching = "Обучение",
        teachingDescription = "Изучайте шахматные техники и стратегии",
        review = "Анализ",
        reviewDescription = "Анализируйте прошлые партии",
        settings = "Настройки",
        settingsDescription = "Персонализированные настройки приложения",
        // SettingsScreen 相关
        language = "Язык",
        aboutUs = "О Нас",
        aboutUsDescription = "Узнайте больше о нас",
        feedback = "Обратная Связь",
        feedbackDescription = "Предоставьте нам ценные отзывы",
        selectLanguage = "Выбрать Язык",
        cancel = "Отмена",
        // 难度选择相关
        difficultyBeginner = "ИИ Новичок",
        difficultyIntermediate = "ИИ Продвинутый",
        difficultyAdvanced = "ИИ Опытный",
        difficultyExpert = "ИИ Эксперт",
        difficultyMaster = "ИИ Мастер",
        difficultyBeginnerDesc = "Подходит для новых игроков в шахматы",
        difficultyIntermediateDesc = "Подходит для игроков с некоторым опытом",
        difficultyAdvancedDesc = "Подходит для регулярных игроков",
        difficultyExpertDesc = "Бросьте вызов ИИ высокого уровня",
        difficultyMasterDesc = "Соревнуйтесь с ИИ высшего уровня",
        // AnalysisScreen 相关的新增字段
        sendingToAI = "Отправка ИИ",
        move = "Ход",
        aiResponse = "Ответ ИИ",
        aiResponseLength = "Длина ответа ИИ",
        parsedItemsCount = "Количество проанализированных элементов",
        analysisItem = "Элемент анализа",
        totalLines = "Всего строк",
        line = "Строка",
        saveAnalysis = "Сохранить анализ",
        foundMove = "Ход найден",
        saveLastAnalysis = "Сохранить последний анализ",
        analysisMapSize = "Размер карты анализа",
        mapItem = "Элемент карты",
        foundAnalysis = "Анализ найден",
        noAnalysis = "ИИ не предоставил конкретного анализа для этого хода.",
        noAnalysisFound = "Анализ не найден",
        fuzzyMatchFound = "Найден нечеткий анализ",
        finalItemsCount = "Окончательно сгенерированные элементы анализа",
        analysis = "Анализ",
        moveNumber = "Номер хода",
        chessboard = "Шахматная доска",
        // 游戏结果相关 - 新增
        resultWhiteWin = "Белые Выиграли",
        resultBlackWin = "Чёрные Выиграли",
        resultDraw = "Ничья",
        resultAIWin = "ИИ Выиграл",
        resultHumanWin = "Человек Выиграл",
        resultCheckmate = "Мат",
        resultStalemate = "Пат",
        resultResignation = "Соперник Сдался",
        resultTimeout = "Время Вышло",
        resultDisconnection = "Соперник Отключился"
    )

    // 获取当前语言环境对应的字符串资源
    @Composable
    fun current(): StringResources {
        return when (Locale.current.language) {
            "zh" -> chinese // 中文
            "ja" -> japanese // 日语
            "ko" -> korean // 韩语
            "es" -> spanish // 西班牙语
            "fr" -> french // 法语
            "de" -> german // 德语
            "ru" -> russian // 俄语
            else -> english // 默认英语
        }
    }

    // 根据语言代码获取字符串资源
    fun getByLanguageCode(languageCode: String): StringResources {
        return when (languageCode) {
            "zh", "zh-CN", "zh-TW" -> chinese
            "ja" -> japanese
            "ko" -> korean
            "es" -> spanish
            "fr" -> french
            "de" -> german
            "ru" -> russian
            else -> english
        }
    }

    // 根据显示名称获取语言代码
    fun getLanguageCodeByDisplayName(displayName: String): String {
        return when (displayName) {
            "中文" -> "zh"
            "English" -> "en"
            "日本語" -> "ja"
            "한국어" -> "ko"
            "Español" -> "es"
            "Français" -> "fr"
            "Deutsch" -> "de"
            "Русский" -> "ru"
            else -> "en"
        }
    }

    // 获取所有支持的语言列表
    fun getSupportedLanguages(): List<Pair<String, String>> {
        return listOf(
            "中文" to "zh",
            "English" to "en",
            "日本語" to "ja",
            "한국어" to "ko",
            "Español" to "es",
            "Français" to "fr",
            "Deutsch" to "de",
            "Русский" to "ru"
        )
    }

    // 获取难度列表的函数
    @Composable
    fun getDifficulties(): List<Difficulty> {
        val strings = current()
        return listOf(
            Difficulty("beginner", "difficultyBeginner", "difficultyBeginnerDesc", "difficultyBeginnerIcon", 1),
            Difficulty("intermediate", "difficultyIntermediate", "difficultyIntermediateDesc", "difficultyIntermediateIcon", 2),
            Difficulty("advanced", "difficultyAdvanced", "difficultyAdvancedDesc", "difficultyAdvancedIcon", 3),
            Difficulty("expert", "difficultyExpert", "difficultyExpertDesc", "difficultyExpertIcon", 4),
            Difficulty("master", "difficultyMaster", "difficultyMasterDesc", "difficultyMasterIcon", 5)
        )
    }

    // 根据键名获取实际字符串值
    fun getDifficultyName(strings: StringResources, nameKey: String): String {
        return when (nameKey) {
            "difficultyBeginner" -> strings.difficultyBeginner
            "difficultyIntermediate" -> strings.difficultyIntermediate
            "difficultyAdvanced" -> strings.difficultyAdvanced
            "difficultyExpert" -> strings.difficultyExpert
            "difficultyMaster" -> strings.difficultyMaster
            else -> ""
        }
    }

    fun getDifficultyDescription(strings: StringResources, descriptionKey: String): String {
        return when (descriptionKey) {
            "difficultyBeginnerDesc" -> strings.difficultyBeginnerDesc
            "difficultyIntermediateDesc" -> strings.difficultyIntermediateDesc
            "difficultyAdvancedDesc" -> strings.difficultyAdvancedDesc
            "difficultyExpertDesc" -> strings.difficultyExpertDesc
            "difficultyMasterDesc" -> strings.difficultyMasterDesc
            else -> ""
        }
    }

    fun getDifficultyIcon(strings: StringResources, iconKey: String): String {
        return when (iconKey) {
            "difficultyBeginnerIcon" -> strings.difficultyBeginnerIcon
            "difficultyIntermediateIcon" -> strings.difficultyIntermediateIcon
            "difficultyAdvancedIcon" -> strings.difficultyAdvancedIcon
            "difficultyExpertIcon" -> strings.difficultyExpertIcon
            "difficultyMasterIcon" -> strings.difficultyMasterIcon
            else -> ""
        }
    }

    // 翻译游戏结果
    fun translateGameResult(chineseResult: String, targetLanguage: StringResources): String {
        return when (chineseResult) {
            "白方获胜" -> targetLanguage.resultWhiteWin
            "黑方获胜" -> targetLanguage.resultBlackWin
            "和棋" -> targetLanguage.resultDraw
            "AI获胜" -> targetLanguage.resultAIWin
            "玩家获胜" -> targetLanguage.resultHumanWin
            "将死获胜" -> targetLanguage.resultCheckmate
            "逼和" -> targetLanguage.resultStalemate
            "对手认输" -> targetLanguage.resultResignation
            "超时判负" -> targetLanguage.resultTimeout
            "对手断线" -> targetLanguage.resultDisconnection
            // 也支持英文结果
            "White Wins" -> targetLanguage.resultWhiteWin
            "Black Wins" -> targetLanguage.resultBlackWin
            "Draw" -> targetLanguage.resultDraw
            "AI Wins" -> targetLanguage.resultAIWin
            "Human Wins" -> targetLanguage.resultHumanWin
            "Checkmate" -> targetLanguage.resultCheckmate
            "Stalemate" -> targetLanguage.resultStalemate
            "Resignation" -> targetLanguage.resultResignation
            "Timeout" -> targetLanguage.resultTimeout
            "Disconnection" -> targetLanguage.resultDisconnection
            else -> chineseResult
        }
    }

    fun translateDifficultyName(chineseName: String, targetLanguage: StringResources): String {
        return when (chineseName) {
            "新手AI" -> targetLanguage.difficultyBeginner
            "入门AI" -> targetLanguage.difficultyIntermediate
            "进阶AI" -> targetLanguage.difficultyAdvanced
            "专家AI" -> targetLanguage.difficultyExpert
            "大师AI" -> targetLanguage.difficultyMaster
            else -> chineseName
        }
    }
}

// 语言状态管理
object LanguageManager {
    var currentLanguageCode by mutableStateOf("zh")

    // 设置语言并保存到 DataStore
    suspend fun setLanguage(context: Context, languageCode: String) {
        currentLanguageCode = languageCode
        // 保存到 DataStore
        PreferenceManager.setLanguage(context, languageCode)
    }

    @Composable
    fun currentStrings(): StringResources {
        return AppStrings.getByLanguageCode(currentLanguageCode)
    }
}

// CompositionLocal 用于在 Compose 树中提供多语言支持
val LocalStrings = staticCompositionLocalOf { AppStrings.english }

// 扩展函数，方便在 Composable 中获取字符串
@Composable
fun strings(): StringResources {
    return LocalStrings.current
}